/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package studio.raptor.ddal.core.engine.plan.node.impl.parse;

import studio.raptor.ddal.core.engine.ProcessContext;
import studio.raptor.ddal.core.engine.plan.node.ProcessNode;

/**
 * 解析SQL语句的注释。
 *
 * @author Sam
 * @since 3.0.0
 */
public class ParseHint extends ProcessNode {

  @Override
  protected void execute(ProcessContext context) {
    context.setSqlHint(deleteCommentHeadTail(context.getOriginSql()));
    context.setHasReadonlyHint(false);
  }

  /**
   * 取注释星号之间的内容，两边星号以外的数据直接丢掉。
   *
   * @param comment 从sql语句中解析出来的注释
   * @return 注释内容，不包含两边的注释修饰符
   */
  private String deleteCommentHeadTail(String comment) {
    StringBuilder commentBuilder = new StringBuilder();
    int firstCharIndex = comment.indexOf("/*!hint", 0);
    if (-1 != firstCharIndex) {
      firstCharIndex += 6;
    }
    char ch;
    for (int i = firstCharIndex + 1, commentLen = comment.length(); i < commentLen; i++) {
      if ((ch = comment.charAt(i)) == '*' && (ch = comment.charAt(i + 1)) == '/') {
        break;
      }
      commentBuilder.append(ch);
    }
    return commentBuilder.toString().trim();
  }
}